#!/bin/bash
if [ "$DR_HOME" == "" ]; then
 printf "DR_HOME envirement variable is not exist\n"
 exit 1
fi
source "$DR_HOME/common/scripts/check.sh"

get_repository_name(){
    check "$DR_IMAGE_DIR"
    app_name=$(basename "$DR_IMAGE_DIR")
    echo "hellomrpc/${app_name}"
}

build(){
    check "$DR_IMAGE_DIR"
    cd "$DR_IMAGE_DIR"
    repository_name=$(get_repository_name)
    
    
    # stop older docker container
    if [ $(docker ps --format '{{.Image}} {{.Names}}' | grep "${repository_name}" | wc -l) -gt 0 ]; then
       docker ps --format '{{.Image}} {{.Names}}' | grep "${repository_name}" | awk '{print $2}' | xargs docker stop 
    fi

    # remove older docker container
    if [ $(docker container ls -a --format '{{.Image}} {{.Names}}' | grep "${repository_name}" | wc -l) -gt 0 ]; then
        docker container ls -a --format '{{.Image}} {{.Names}}' | grep "${repository_name}" | awk '{print $2}' | xargs docker rm
    fi

    # remove older docker image
    if [ $(docker image ls | grep "${repository_name}" | wc -l) -gt 0 ]; then
        docker image ls | grep "${repository_name}" | awk '{print $3}' | xargs docker rmi
    fi    
    
    docker build -t "${repository_name}" .
}

push(){
    if [ $(docker info | grep "Username: hellomrpc" | wc -l) -eq 0 ]; then
        printf 'please login first\n'
        exit 1
    fi
    repository_name=$(get_repository_name)
    docker push "${repository_name}"
}